using System;
using System.Collections.Generic;

namespace AlgoLogicMessengerCompetitor
{
    //AI for the computer, this decides what the next move should be
    public class AI
    {
        private readonly BoardPosition[,,] gameMatrix;
        private readonly int dimension;
        private readonly Random randomNumber = new Random();

        public AI(BoardPosition[,,] grid, int dim)
        {
            gameMatrix = grid;
            dimension = dim;
        }

        //public AI(BoardPosition[,,] grid, int dim)
        //{
        //    gameMatrix = grid;
        //    dimension = dim;
        //}

        public Move NextAIMove(PlayerNumber computerPlayer)
        {
            int highestImportance = 0;
            Move desiredMove = null;
            bool oneAwayMoveAllowed = false;
            bool twoAwayMoveAllowed = false;

            for (int i = 0; i < dimension; i++)
            {
                for (int j = 0; j < dimension; j++)
                {
                    for (int k = 0; k < dimension; k++)
                    {
                        if (gameMatrix[i, j, k].ImportanceFactor >= 99 && oneAwayMoveAllowed)
                        {
                            desiredMove = gameMatrix[i, j, k].Move;
                            desiredMove.Player = computerPlayer;
                            return desiredMove;
                        }
                        else if (gameMatrix[i, j, k].ImportanceFactor < 99)
                        {
                            if (highestImportance < gameMatrix[i, j, k].ImportanceFactor)
                            {
                                highestImportance = gameMatrix[i, j, k].ImportanceFactor;
                                desiredMove = gameMatrix[i, j, k].Move;
                                desiredMove.Player = computerPlayer;
                            }
                        }
                    }
                }
            }

            if (twoAwayMoveAllowed)
            {
                return desiredMove;
            }
            else
            {
                return NextAIRandomMove(computerPlayer);
            }
        }

        public Move NextAIRandomMove(PlayerNumber computerPlayer)
        {
            int x = 0;
            int y = 0;
            int z = 0;

            do
            {
                x = randomNumber.Next(0, dimension);
                y = randomNumber.Next(0, dimension);
                z = randomNumber.Next(0, dimension);
            } while (gameMatrix[x, y, z].Player != PlayerNumber.None);

            Move desiredMove = gameMatrix[x, y, z].Move;
            desiredMove.Player = computerPlayer;

            return desiredMove;
        }
    }
}